package cn.jee.cs.controller;

import cn.jee.cs.repo.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.jee.cs.model.Student;
import cn.jee.cs.model.validation.OnCreate;
import cn.jee.cs.model.validation.OnEdit;

@Controller
@RequestMapping("/student")
public class StudentController {
  @Autowired
  private StudentRepository studentRepository;

  /**
   * 查询所有学生信息
   * 
   * @param model
   * @return 并返回学生列表信息页面 student/index.html
   */
  @GetMapping("")
  public String showStudentsPage(Model model) {
    model.addAttribute("students", studentRepository.findAll());
    return "student/index";
  }

  /**
   * 查询学生详细信息,如果没查到，返回错误信息
   * 
   * @param model 视图的模型容器
   * @return 返回学生信息页面student/student.html
   */
  @GetMapping("/view")
  public String showStudentPage(@RequestParam("id") Student student, Model model) {
    model.addAttribute("student", student);
    return "student/student";
  }

  /**
   * 删除学生并重定向到/student,显示全部学生
   * 
   * @param id    前端传来的学生id
   * @return 重定向到 /student
   */
  @GetMapping("/delete")
  public String deleteStudent(@RequestParam("id") Long id) {
    studentRepository.deleteById(id);
    return "redirect:/student";
  }

  /** 
   * 弹出添加或修改学生的表单页面form.html

   * @param model 视图的模型容器
   * @return 返回表单页面student/form.html
   */
  @GetMapping("/form")
  public String showFormPage(@RequestParam(value="id", required = false) Student student,
                             Model model) {
    if(student == null){
      student = new Student();
    }
    model.addAttribute("student",student);
    return "student/form";
  }

  /**
   * 增加学生
   * @param student 领域对象
   * @param bindingResult 领域对象绑定结果 
   * @return 当验证不通过时返回到form.html，否则重定向到 /student进行添加所有学生的显示
   */
  @PostMapping("/add")
  public String addStudent(@Validated(OnCreate.class)  Student student, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
      // 有错误是回到form，此处同时自动把bindingResult绑定到form.html视图
      return "student/form";    
    }else {
      studentRepository.save(student);
  
      return "redirect:/student";
    }
  }

  /**
   * 修改学生
   * @param student 领域对象
   * @param bindingResult 绑定结果
   * @return 验证失败回到form.html表单页面,否则重定向到/student显示学生列表
   */
  @PostMapping("/edit")
  public String editStudent(
      @Validated(OnEdit.class) Student student, 
      BindingResult bindingResult) {
    
    if(bindingResult.hasErrors()) {
      return "student/form";
    }else {
      studentRepository.save(student);
      return "redirect:/student";
    }
  }
}
